from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.tokens import RefreshToken

import json

# Create your views here.


def login_view(request):
    if request.method == "POST":
        pass
    return render(request, "login_page.html")

@api_view(['POST'])
@permission_classes([AllowAny])
def login_api(request):
    # 是培育drf
    username = request.data.get("username")
    password = request.data.get("password")

    # 验证用户登录
    user = authenticate(request, username=username, password=password)
    if user is not None:
        # 1️ Django 内部登录（生成 session id、绑定 user）
        login(request, user)
        # 2️ 额外写入自定义信息，供后续使用
        messages.success(request, '登录成功！')
        # 3 生成token
        refresh = RefreshToken.for_user(user)
        access_token = str(refresh.access_token)

        # 3️ 跳转到首页或 next
        # 返回用户信息
        return Response({
            'success': True,
            'token': access_token,
            'refresh_token': str(refresh),
            'user': {
                'username': user.username,
                'first_name': user.first_name,
                'last_name': user.last_name,
                'phone_number': user.phone_number
            }
        }, status=status.HTTP_200_OK)
    else:
        return Response({
            'success': False,
            'message': '用户名或密码错误',
            'code': 'failed'
        }, status=status.HTTP_200_OK)

@api_view(['POST'])
@permission_classes([AllowAny])
def logout_view(request):
    """退出登录"""
    logout(request)
    messages.info(request, '已退出登录')
    return Response({
        "success": True,
        "message": "已退出登录"
    }, status=status.HTTP_200_OK)

@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])  # 需要认证才允许访问
def verify_token(request):
    # 如果请求能走到这里，说明 token 有效
    return Response({"valid": True})